<?php


namespace app\common\lib\redis;


class Predis
{
    public $redis = "";
    /**
     * 定义单例模式的变量
     * @var null
     */
    private static $_instance = null;

    public static function getInstance()
    {
        if(empty(self::$_instance))
        {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    private function __construct()
    {
        $this->redis= new \Redis();
        $result  = $this->redis->connect(config('redis.host'),config('redis.port'),config('redis.timeOut'));
        if($result == false)
        {
              throw new \Exception('redis connect error');
        }
    }

    /**
     * redis set 方法
     * @param $key
     * @param $value
     * @param $time
     * @return bool|string
     */
    public function set($key,$value,$time=0)
    {
        if(!$key){
            return "";
        }
        if(is_array($value)){
            $value = json_encode($value);
        }
        if(!$time)
        {
            return $this->redis->set($key,$value);
        }
        return $this->redis->setex($key,$time,$value);
    }

    /**
     * redis 的 get 方法
     * @param $key
     * @return string
     */
    public  function get($key)
    {
        if(!$key)
        {
            return "";
        }

        return $this->redis->get($key);
    }

    /**
     * @param $key
     * @param $value
     * @return mixed
     */
    public function sAdd($key,$value){
        return $this->redis->sAdd($key,$value);
    }

    /**
     * 删除有序集合
     * @param $key
     * @param $value
     * @return int
     */
    public function sRem($key,$value){
        return $this->redis->sRem($key,$value);

    }

    /**
     * @param $key
     * @return array
     */
    public function sMembers($key)
    {
        return $this->redis->sMembers($key);

    }
    public function __call($name,$data){
        return $this->redis->$name($data[0],$data[1]);
    }
}